import { useEffect, useMemo } from 'react';
import { Howl, HowlOptions } from 'howler';

interface IUseHowlOptions extends Omit<HowlOptions, 'src'> {
  autoPlay?: boolean;
}

/**
 * Howl hook 实现预加载
 * @param src 资源地址
 * @param options 属性
 * @returns Howl 实例
 */
export function useHowl(src: string | string[] | undefined, options?: IUseHowlOptions) {

  const howl = useMemo(() => {
    const _howl = src ? new Howl({
      src,
      autoplay: options?.autoPlay,
      volume: options?.volume,
    }) : undefined;
    return _howl;
  }, [src, options?.volume, options?.autoPlay]);

  useEffect(() => {
    return () => {
      howl?.unload();
    };
  }, [howl]);

  return howl;
}